<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入车次编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="date">
        <el-date-picker clearable v-model="queryParams.date" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="start">
        <el-input v-model="queryParams.start" placeholder="请输入始发站" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="end">
        <el-input v-model="queryParams.end" placeholder="请输入终点站" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
<!--          v-hasPermi="['business:daily-train:add']">新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"-->
<!--          v-hasPermi="['business:daily-train:edit']">修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"-->
<!--          v-hasPermi="['business:daily-train:remove']">删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:daily-train:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="" size="mini" @click="handleXinXi"
          v-hasPermi="['business:daily-train:add']">手动生成车次信息
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 使用折叠面板展示分组数据 -->
    <el-collapse v-loading="loading">
      <el-collapse-item v-for="(group, index) in groupedTrains" :key="index" :name="index">
        <template slot="title">
          <div class="train-group-title">
            <span class="train-code">车次: {{ group.code }}</span>
            <span class="train-route">
              {{ group.start }}
              <span class="station-type">({{ getStationType(group.type) }})</span>
              → {{ group.end }}
              <span class="station-type">({{ getStationType(group.type) }})</span>
            </span>
          </div>
        </template>

        <!-- 嵌套表格显示具体车次信息 -->
        <el-table :data="group.trains" :row-style="{ height: '60px' }" @selection-change="handleSelectionChange">
<!--          <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />-->
          <el-table-column show-overflow-tooltip label="序号" type="index" width="50" align="center" />
          <el-table-column show-overflow-tooltip label="ID" align="center" prop="id" width="170px" />
          <el-table-column show-overflow-tooltip label="日期" align="center" prop="date" width="120px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="车次编号" align="center" prop="code" width="120px"  />
          <el-table-column show-overflow-tooltip label="车次类型" align="center" width="110px" >
            <template slot-scope="scope">
              <span>{{ getStationType(scope.row.type).replace('站', '') }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="始发/终点站" align="center">
            <template slot-scope="scope">
              <span>
                {{ scope.row.start }}
                <span class="station-tag">({{ getStationType(scope.row.type) }})</span>
                → {{ scope.row.end }}
                <span class="station-tag">({{ getStationType(scope.row.type) }})</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="发车/到站时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.startTime }} → {{ scope.row.endTime }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="运行时间" align="center">
            <template slot-scope="scope">
              <span>{{ calculateDuration(scope.row.startTime, scope.row.endTime) }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
<!--                v-hasPermi="['business:daily-train:edit']">修改</el-button>-->
<!--              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['business:daily-train:remove']">删除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 展示手动生成车次信息按钮 -->
    <!-- 手动车次信息-->
    <el-dialog :title="title" :visible.sync="XinXiOpen" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="日期" prop="createDate">
          <el-date-picker clearable v-model="form.createDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitXinXi">确 定</el-button>
        <el-button @click="Xinxicancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改每日车次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable v-model="form.date" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车次编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入车次编号" />
        </el-form-item>
        <el-form-item label="车次类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择车次类型">
            <el-option label="G-高铁" value="G" />
            <el-option label="D-动车" value="D" />
            <el-option label="K-快速" value="K" />
            <el-option label="T-特快" value="T" />
            <el-option label="Z-直达" value="Z" />
          </el-select>
        </el-form-item>
        <el-form-item label="始发站" prop="start">
          <el-input v-model="form.start" placeholder="请输入始发站" />
        </el-form-item>
        <el-form-item label="始发拼音" prop="startPinyin">
          <el-input v-model="form.startPinyin" placeholder="请输入始发站拼音" />
        </el-form-item>
        <el-form-item label="出发时间" prop="startTime">
          <el-time-picker v-model="form.startTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="请选择出发时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="终点站" prop="end">
          <el-input v-model="form.end" placeholder="请输入终点站" />
        </el-form-item>
        <el-form-item label="终点拼音" prop="endPinyin">
          <el-input v-model="form.endPinyin" placeholder="请输入终点站拼音" />
        </el-form-item>
        <el-form-item label="到站时间" prop="endTime">
          <el-time-picker v-model="form.endTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="请选择到站时间">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDailyTrainByGroup, getDailyTrain, delDailyTrain, addDailyTrain, updateDailyTrain, genDailyTrain } from "@/api/business/daily-train";

export default {
  name: "DailyTrain",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 每日车次表格数据
      groupedTrains: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        code: null,
        type: null,
        start: null,
        end: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "车次编号不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "车次类型不能为空", trigger: "change" }
        ],
        start: [
          { required: true, message: "始发站不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "出发时间不能为空", trigger: "change" }
        ],
        end: [
          { required: true, message: "终点站不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "到站时间不能为空", trigger: "change" }
        ]
      },
      XinXiOpen: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询每日车次列表 */
    getList() {
      this.loading = true;
      listDailyTrainByGroup(this.queryParams).then(response => {
        this.groupedTrains = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取站点类型
    getStationType(type) {
      if (type === 'G') {
        return '高铁站';
      } else if (type === 'D') {
        return '火车站';
      } else {
        return '综合站';
      }
    },
    // 计算运行时间
    calculateDuration(startTime, endTime) {
      if (!startTime || !endTime) {
        return '未知';
      }

      // 转换为分钟
      const start = startTime.split(':');
      const end = endTime.split(':');

      let startMinutes = parseInt(start[0]) * 60 + parseInt(start[1]);
      let endMinutes = parseInt(end[0]) * 60 + parseInt(end[1]);

      // 如果结束时间小于开始时间，说明跨天了
      if (endMinutes < startMinutes) {
        endMinutes += 24 * 60;
      }

      const durationMinutes = endMinutes - startMinutes;
      const hours = Math.floor(durationMinutes / 60);
      const minutes = durationMinutes % 60;

      return `${hours}小时${minutes}分钟`;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        code: null,
        type: null,
        start: null,
        startPinyin: null,
        startTime: null,
        end: null,
        endPinyin: null,
        endTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每日车次";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailyTrain(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每日车次";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDailyTrain(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDailyTrain(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每日车次编号为"' + ids + '"的数据项？').then(function () {
        return delDailyTrain(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/daily-train/export', {
        ...this.queryParams
      }, `daily-train_${new Date().getTime()}.xlsx`)
    },
    //车次信息
    Xinxicancel() {
      this.XinXiOpen = false;
    },
    /** 车次信息按钮操作 */
    handleXinXi() {
      this.XinXiOpen = true;
      this.title = "生成车次";
    },
    /** 车次信息提交按钮 */
    submitXinXi() {
      console.log(this.form.createDate)
      if (this.form.createDate != null) {
        genDailyTrain(this.form.createDate).then(response => {
          this.$modal.msgSuccess("生成成功");
          this.XinXiOpen = false;
          this.getList();
        });
      }
    }
  }
};
</script>

<style>
/* 折叠面板相关样式 */
.train-group-title {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.train-code {
  font-weight: bold;
  margin-right: 20px;
  min-width: 80px;
}

.train-route {
  min-width: 200px;
  color: #606266;
}

.station-type {
  font-size: 12px;
  color: #909399;
}

.station-tag {
  font-size: 12px;
  color: #909399;
  margin: 0 2px;
}

.el-collapse-item__header {
  height: 60px;
  line-height: 60px;
  background-color: #f5f7fa;
  padding-left: 15px;
}

.el-collapse-item__content {
  padding: 10px;
}
</style>
